package com.yingpai.fitness.dvp_2_0.main.activity.vip;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.Permission;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.main.bean.integral.IntegralVipCardBean;
import com.yingpai.fitness.dvp_2_0.main.bean.IsSuccessBean;
import com.yingpai.fitness.dvp_2_0.main.util.PayUtil;
import com.yingpai.fitness.base.BaseResponse;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.ProtocolActivity;
import com.yingpai.fitness.dvp_2_0.main.callback.WechatCallBack;
import com.yingpai.fitness.dvp_2_0.main.util.WechatLoginUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.vip_card.ALiPayBean;
import com.yingpai.fitness.entity.vip_card.BuyVipBean;
import com.yingpai.fitness.entity.vip_card.MemberInfoBean;
import com.yingpai.fitness.entity.vip_card.NotVipListBean;
import com.yingpai.fitness.entity.vip_card.WeChatPayBean;
import com.yingpai.fitness.entity.wx.TokenBean;
import com.yingpai.fitness.dvp_2_0.main.util.IdCardUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;

/**
 * Created by ASUS on 2018/8/13.
 */

public class BuyVipCardActivity extends CommonActivity implements PayUtil.codeResultClickInterface, WechatCallBack {

    @BindView(R.id.user_photo)
    CircleImageView userPhoto;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.buyInputNameEt)
    EditText buyInputNameEt;
    @BindView(R.id.buyInputTelEt)
    EditText buyInputTelEt;
    @BindView(R.id.identification)
    EditText identification;
    @BindView(R.id.takePhotoIv)
    ImageView takePhotoIv;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.money_tv)
    TextView money_tv;
    @BindView(R.id.sum)
    TextView sum;
    @BindView(R.id.weChatPayCb)
    CheckBox weChatPayCb;
    @BindView(R.id.aLiPayCb)
    CheckBox aLiPayCb;
    @BindView(R.id.nested_scroll_view)
    NestedScrollView nestedScrollView;
    @BindView(R.id.vipRl)
    RelativeLayout vipRl;
    @BindView(R.id.sum_integral)
    TextView sum_integral;
    @BindView(R.id.sum_ll)
    LinearLayout sumLl;
    @BindView(R.id.wechat_rl)
    RelativeLayout wechatRl;
    @BindView(R.id.alpay_rl)
    RelativeLayout alpayRl;
    @BindView(R.id.card_money)
    TextView card_money;
    private LayoutInflater mInflater;
    private LinearLayout dialog_takephoto_warring;
    private Dialog dialog;
    private File file;
    private String WeChatOrAlipay = "";
    private NotVipListBean.MapData.VipCardListData vipInfo;
    private MemberInfoBean infomation;
    private TokenBean tokenBean;
    private BuyVipBean mBuyVipBean;
    private DecimalFormat df = new DecimalFormat("######.###");
    private String cardPrice;
    private String id;
    private String integral;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_buy_vip_card);
    }

    @Override
    protected void initView() {
        setTitle("健身会员");
        mInflater = LayoutInflater.from(this);

        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            cardPrice = bundle.getString("cardPrice");
            id = bundle.getString("id");
            integral = bundle.getString("integral");
            vipInfo = (NotVipListBean.MapData.VipCardListData) bundle.getSerializable("vipInfo");
            infomation = (MemberInfoBean) bundle.getSerializable("infomation");
        }

        userName.setText(infomation.getMap().getCustomer().getNickName() + "");
        Glide.with(BuyVipCardActivity.this)
                .load(infomation.getMap().getCustomer().getPhotoUrl())
                .error(R.mipmap.icon_user_default)
                .centerCrop()
                .into(userPhoto);
        if(!TextUtils.isEmpty(cardPrice)){
            money_tv.setText("积分兑换：");
            money.setText(integral);
            sumLl.setVisibility(View.GONE);
            wechatRl.setVisibility(View.GONE);
            alpayRl.setVisibility(View.GONE);
            sum_integral.setVisibility(View.VISIBLE);
            card_money.setVisibility(View.VISIBLE);
            card_money.setText("￥"+cardPrice);
        }else{
            money.setText("￥" + df.format(vipInfo.getCard_price() / 100));
        }

        final int startColor = ContextCompat.getColor(this, R.color.normal_status);
        final int endColor = ContextCompat.getColor(this, R.color.colorNavigation);

        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int headHeight = vipRl.getHeight();
                int scrollDistance = Math.min(scrollY, headHeight);
                float fraction = (float) scrollDistance / (float) headHeight;

//                setToolbarStatusBarAlpha(evaluate(fraction, startColor, endColor),titleBar);
                setNavigationViewColor(evaluate(fraction, startColor, endColor));
            }
        });
    }

    @Override
    protected void initData() {

    }

    private void showTakePhotoOrAlbumDialog() {
        TDialog tDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.take_photos_dialog_layout)
                .setScreenWidthAspect(this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .addOnClickListener(R.id.tv_open_camera, R.id.tv_open_album, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_open_camera:
                                FunctionConfig camera = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .setCropSquare(true)
                                        .build();
                                //带配置
                                GalleryFinal.openCamera(300, camera, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 300) {
                                            file = new File(resultList.get(0).getPhotoPath());
                                            Glide.with(BuyVipCardActivity.this)
                                                    .load(resultList.get(0).getPhotoPath())
                                                    .into(takePhotoIv);
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_open_album:
                                FunctionConfig album = new FunctionConfig.Builder()
                                        .setEnableEdit(true)
                                        .setEnableCrop(true)
                                        .setEnableRotate(true)
                                        .setCropSquare(true)
                                        .setEnablePreview(true)
                                        .build();
                                //带配置
                                GalleryFinal.openGallerySingle(200, album, new GalleryFinal.OnHanlderResultCallback() {
                                    @Override
                                    public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                                        if (reqeustCode == 200) {
                                            file = new File(resultList.get(0).getPhotoPath());
                                            Glide.with(BuyVipCardActivity.this)
                                                    .load(resultList.get(0).getPhotoPath())
                                                    .into(takePhotoIv);
                                        }
                                    }

                                    @Override
                                    public void onHanlderFailure(int requestCode, String errorMsg) {

                                    }
                                });
                                tDialog.dismiss();
                                break;
                            case R.id.tv_cancel:

                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();

    }

    private void showWarringDialog() {
        dialog_takephoto_warring = (LinearLayout) mInflater.inflate(R.layout.dialog_takephoto_warring, null);
        dialog = new AlertDialog.Builder(this, R.style.NoBackGroundDialog).create();

        dialog_takephoto_warring.findViewById(R.id.sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (rxPermissions.isGranted(Manifest.permission.CAMERA) && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    showTakePhotoOrAlbumDialog();
                } else {
                    rxPermissions.requestEach(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Permission>() {
                                @Override
                                public void accept(Permission permission) throws Exception {
                                    if (permission.granted) {
                                        // 用户已经同意该权限
                                        showTakePhotoOrAlbumDialog();
                                    } else if (permission.shouldShowRequestPermissionRationale) {
                                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                                        showToast("拒绝权限可能导致部分功能不能使用");
                                    } else {
                                        // 用户拒绝了该权限，并且选中『不再询问』
                                        showToast("拒绝权限可能导致部分功能不能使用，如果需要请在设置中修改");
                                    }
                                }
                            });
                }
            }
        });
    }

    @Override
    public void ZFBSuccess(String code) {
        dismissDialog();
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", tokenBean.getId());
        httpParams.put("orderId", mBuyVipBean.getMap().getVipOrderid());
        httpParams.put("payMode", Constant.NUM_1);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.NOTIFY_PAY, httpParams, Url.NOTIFY_PAY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    EventBus.getDefault().post(Constant.REQUEST_SUCCESS);
                    finish();
                } else {
                    showToast(baseResponse.getMsg());
                }
            }
            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    @Override
    public void ZFBFail(String code) {
        dismissDialog();
        showToast("支付失败");
    }

    @Override
    public void ZFBResultQueRen(String code) {

    }


    @Override
    @OnClick({R.id.vip_question, R.id.vip_crown, R.id.takePhotoIv, R.id.subtract, R.id.add, R.id.weChatPayCb, R.id.aLiPayCb, R.id.buy})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.vip_question:
                Bundle bundle = new Bundle();
                bundle.putString("title", "会员须知");
                startActivity(ProtocolActivity.class, bundle);
                break;
            case R.id.vip_crown:
                Bundle bundle1 = new Bundle();
                bundle1.putString("title", "会员专属");
                startActivity(ProtocolActivity.class, bundle1);
                break;
            case R.id.takePhotoIv:
                showWarringDialog();
                dialog.show();
                dialog.setContentView(dialog_takephoto_warring);
                break;
            case R.id.subtract:
                if (Integer.parseInt(sum.getText().toString()) == 1) {
                    showToast("数量不能小于一");
                } else {
                    sum.setText(Integer.parseInt(sum.getText().toString()) - 1 + "");
                }
                break;
            case R.id.add:
                sum.setText(Integer.parseInt(sum.getText().toString()) + 1 + "");
                break;
            case R.id.weChatPayCb:
                if (weChatPayCb.isChecked()) {
                    WeChatOrAlipay = Constant.WECHAT;
                    aLiPayCb.setChecked(false);
                } else {
                    WeChatOrAlipay = "";
                }
                break;
            case R.id.aLiPayCb:
                if (aLiPayCb.isChecked()) {
                    WeChatOrAlipay = Constant.ALIPAY;
                    weChatPayCb.setChecked(false);
                } else {
                    WeChatOrAlipay = "";
                }
                break;
            case R.id.buy:
                if (!TextUtils.isEmpty(buyInputNameEt.getText().toString().trim()) &&
                        !TextUtils.isEmpty(buyInputTelEt.getText().toString().trim()) &&
                        !TextUtils.isEmpty(identification.getText().toString().trim())) {
                    if (new IdCardUtil(identification.getText().toString().trim()).isCorrect() == 0) {
                        if (file != null) {
                            if(!TextUtils.isEmpty(cardPrice)){
                                showDialog(this,null);
                                HashMap<String,Object> map = new HashMap<>();
                                map.put("id",id);
                                finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.EXCHANGE_VIP_CARD, map, Url.EXCHANGE_VIP_CARD, new Callback<IntegralVipCardBean>() {
                                    @Override
                                    public void onSuccess(IntegralVipCardBean integralVipCardBean) {
                                        if(integralVipCardBean.getCode().equals(Constant.REQUEST_SUCCESS_0)){
                                            HashMap<String,Object> map = new HashMap<>();
                                            map.put("name",buyInputNameEt.getText().toString().trim());
                                            map.put("id",integralVipCardBean.getData().getId());
                                            map.put("phoneNumber", buyInputTelEt.getText().toString().trim());
                                            map.put("idNumber", identification.getText().toString().trim());
                                            map.put("sl", sum.getText().toString());
                                            map.put("__file", file);
                                            finalOkGo.requestEncrypt(RequestType.POSTFILESENCRYPT,
                                                    Contacts.HOST_SERVER + Url.SURE_EXCHANGE_VIP_CARD,
                                                    map, Url.SURE_EXCHANGE_VIP_CARD, new Callback<IsSuccessBean>() {
                                                @Override
                                                public void onSuccess(IsSuccessBean isSuccessBean) {
                                                    dismissDialog();
                                                    if(isSuccessBean.getCode().equals(Constant.REQUEST_SUCCESS_0)){
                                                        startActivity(VipCardActivity.class);
                                                        EventBus.getDefault().post("==exchange==");
                                                        EventBus.getDefault().post("finish");
                                                        finishActivity();
                                                    }else{
                                                        showToast(isSuccessBean.getMessage()+"");
                                                    }
                                                }

                                                @Override
                                                public void onError(Response<String> response) {
                                                    super.onError(response);
                                                    dismissDialog();
                                                }
                                            });
                                        }else{
                                            dismissDialog();
                                            showToast(integralVipCardBean.getMessage()+"");
                                        }
                                    }

                                    @Override
                                    public void onError(Response<String> response) {
                                        super.onError(response);
                                        dismissDialog();
                                    }
                                });
                            }else{
                                if (!"".equals(WeChatOrAlipay)) {
                                    showDialog(this, "支付中...");
                                    HttpParams httpParams = new HttpParams();
                                    httpParams.put("customerId", tokenBean.getId());
                                    httpParams.put("vipcardId", vipInfo.getId());
                                    httpParams.put("name", buyInputNameEt.getText().toString().trim());
                                    httpParams.put("phoneNumber", buyInputTelEt.getText().toString().trim());
                                    httpParams.put("idNumber", identification.getText().toString().trim());
                                    httpParams.put("sl", sum.getText().toString());
                                    httpParams.put("file", file);
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.COMMIT_INFO_VIP, httpParams, Url.COMMIT_INFO_VIP, new Callback<BuyVipBean>() {
                                        @Override
                                        public void onSuccess(BuyVipBean buyVipBean) {
                                            mBuyVipBean = buyVipBean;
                                            if (Constant.REQUEST_SUCCESS.equals(buyVipBean.getResult())) {
                                                if (WeChatOrAlipay.equals(Constant.WECHAT)) {
                                                    HttpParams params = new HttpParams();
                                                    params.put("customerId", tokenBean.getId());
                                                    params.put("vipOrderNumber", buyVipBean.getMap().getVipOrderid());
                                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.WECHAT_PAY, params, Url.WECHAT_PAY, new Callback<WeChatPayBean>() {
                                                        @Override
                                                        public void onSuccess(WeChatPayBean weChatPayBean) {
                                                            if (weChatPayBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                                WechatLoginUtil.getInstance().setWechatCallBack(BuyVipCardActivity.this);
                                                                PayUtil.wxpay(getApplicationContext(), weChatPayBean.getMap().getResponse().getAppid(),
                                                                        weChatPayBean.getMap().getResponse().getPartnerid(),
                                                                        weChatPayBean.getMap().getResponse().getPrepayid(),
                                                                        weChatPayBean.getMap().getResponse().getNoncestr(),
                                                                        weChatPayBean.getMap().getResponse().getTimestamp() + "",
                                                                        weChatPayBean.getMap().getResponse().getSign());
                                                            } else {
                                                                showToast(weChatPayBean.getMsg());
                                                            }
                                                        }

                                                        @Override
                                                        public void onError(Response<String> response) {
                                                            super.onError(response);
                                                            dismissDialog();
                                                        }
                                                    });
                                                } else if (Constant.ALIPAY.equals(WeChatOrAlipay)) {
                                                    HttpParams params = new HttpParams();
                                                    params.put("customerId", tokenBean.getId());
                                                    params.put("vipOrderNumber", buyVipBean.getMap().getVipOrderid());
                                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.ALI_PAY, params, Url.ALI_PAY, new Callback<ALiPayBean>() {
                                                        @Override
                                                        public void onSuccess(ALiPayBean aLiPayBean) {
                                                            if (aLiPayBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                                                                PayUtil.zfbpay(BuyVipCardActivity.this, BuyVipCardActivity.this, aLiPayBean.getMap().getResponse());
                                                            } else {
                                                                showToast(aLiPayBean.getMsg());
                                                            }
                                                        }
                                                        @Override
                                                        public void onError(Response<String> response) {
                                                            super.onError(response);
                                                            dismissDialog();
                                                        }
                                                    });
                                                }
                                            } else {
                                                dismissDialog();
                                                showToast(buyVipBean.getMsg());
                                            }
                                        }
                                    });
                                } else {
                                    showToast("请选择支付方式");
                                }

                            }
                        } else {
                            showToast("请上传照片");
                        }
                    } else {
                        showToast("身份证号不正确");
                    }

                } else {
                    showToast("请填写完整信息");
                }

                break;
        }
    }

    @Override
    public void callBack(BaseResp baseResp) {
        dismissDialog();
        if(baseResp.errCode != BaseResp.ErrCode.ERR_OK){
            return;
        }
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", tokenBean.getId());
        httpParams.put("orderId", mBuyVipBean.getMap().getVipOrderid());
        httpParams.put("payMode", Constant.NUM_2);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.NOTIFY_PAY, httpParams, Url.NOTIFY_PAY, new Callback<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse baseResponse) {
                if (baseResponse.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    EventBus.getDefault().post(Constant.REQUEST_SUCCESS);
                    finish();
                } else {
                    showToast(baseResponse.getMsg());
                }
            }
            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }
}
